package yw.substart.example.util;

import com.alibaba.fastjson.JSON;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.io.*;
import java.util.HashMap;
import java.util.Map;

/**
 * @author lwq 2018/5/22
 * @comment
 */
@Component
public class Config {

    private final static Logger logger = LoggerFactory.getLogger(Config.class);

    public static Map<String, Map> configMap = new HashMap<>();
    private static boolean IS_READ_CONFIG = false;//是否已读取过配置文件

    private static String path = "substart.config";

    public Config() {
        read();
    }

    /**
     * 读取配置文件到 configMap
     */
    public static void read() {
        if (IS_READ_CONFIG) return;
        FileInputStream fileInputStream = null;
        InputStreamReader inputStreamReader = null;
        BufferedReader bufferedReader = null;
        try {
            File file = new File(path);
            logger.info(path);
            if (!file.exists()) {
                file.createNewFile();
                return;
            }
            fileInputStream = new FileInputStream(file);
            inputStreamReader = new InputStreamReader(fileInputStream, "UTF-8");
            bufferedReader = new BufferedReader(inputStreamReader);
            String text;
            String[] strings;
            while ((text = bufferedReader.readLine()) != null) {
                if (!text.contains("?")) {
                    logger.warn("格式不正确，跳过此行数据");
                    logger.info(text);
                    continue;
                }
                strings = text.split("\\?");
                if (strings.length != 2) {
                    logger.warn("数据不正确，跳过");
                    logger.info(text);
                    continue;
                }
                configMap.put(strings[0], (Map) JSON.parse(strings[1]));
            }
            logger.info("-= 读取配置完成 =-");
            IS_READ_CONFIG = true;
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        } finally {
            try {
                if (bufferedReader != null) bufferedReader.close();
                if (inputStreamReader != null) inputStreamReader.close();
                if (fileInputStream != null) fileInputStream.close();
            } catch (IOException e) {
                logger.error("关闭文件流时发生异常", e);
            }
        }
    }

    private static StringBuilder content() {
        StringBuilder stringBuilder = new StringBuilder();
        for (String key : configMap.keySet()) {
            stringBuilder.append(key).append("?").append(JSON.toJSONString(configMap.get(key))).append("\r\n");
        }
        return stringBuilder;
    }


    /**
     * 写入配置文件到 configMap
     */
    public static void write() {
        File file = new File(path);
        FileWriter fw = null;
        BufferedWriter bw = null;
        try {
            if (!file.exists()) {
                file.createNewFile();
            }
            fw = new FileWriter(file, false);
            bw = new BufferedWriter(fw);
            bw.write(content().toString());
            bw.flush();
            fw.flush();
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        } finally {
            try {
                if (bw != null) bw.close();
                if (fw != null) fw.close();
            } catch (IOException e) {
                logger.error("关闭文件流时发生异常", e);
            }
        }
    }

}
